<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>图片懒加载</title>
<style>
    div{ width: 800px; margin: 0 auto; margin-left:800px;}
    img{ width:50%; height: 200px; margin: 100px auto;}
    </style>
</head>
<body style="height:2800px; background:#F1F1F1">
<div>
<!-- 第一步；我们先添加几张图片，作为测试图片 -->
<img data-src="https://img.php.cn/upload/course/000/000/001/636b190e76c19501.png"  src="https://www.php.cn/static/images/moren/morentu.png">
<img data-src="https://img.php.cn/upload/course/000/000/001/6292e3ff192a9960.png"  src="https://www.php.cn/static/images/moren/morentu.png">
<img data-src="https://img.php.cn/upload/course/000/000/068/63368f77cf7bb697.png"  src="https://www.php.cn/static/images/moren/morentu.png">
<img data-src="https://img.php.cn/upload/course/000/000/068/626a7835292d3241.jpg"  src="https://www.php.cn/static/images/moren/morentu.png">
<img data-src="https://img.php.cn/upload/course/000/000/015/61a08af7104fb653.jpg"  src="https://www.php.cn/static/images/moren/morentu.png">
<img data-src="https://img.php.cn/upload/course/000/000/068/6250f8dd38efe771.png"  src="https://www.php.cn/static/images/moren/morentu.png">
<img data-src="https://img.php.cn/upload/aroundimg/000/000/001/62fdcfb67b3b8383.png"  src="https://www.php.cn/static/images/moren/morentu.png">
</div>
<script>
    //第二步：用intersectionObserver实现懒加载
    const imgs = [...document.getElementsByTagName('img')]
            // 当监听的元素进入可视范围内的会触发回调
            if(IntersectionObserver){
                let lazyloadObser = new IntersectionObserver((entries,observer)=>{
                    entries.forEach((entry,index) =>{
                        let lazyImage = entry.target
                        // 那么如何判断此时元素是进入视口还是退出视口呢?
                        // 通过entry.intersectionRatio属性
                        // 元素在页面中的面积大于0，则元素出现在视口中，即元素进入视口
                        if(entry.intersectionRatio>0){  
                            //进入视口后把真实的图片地址赋给图片的src，使得图片展示出来
                            lazyImage.src = lazyImage.getAttribute('data-src');
                            // 当前图片加载完之后需要去掉监听
                            lazyloadObser.unobserve(lazyImage)
                        }
                    })
                })  
              for(let i = 0; i < imgs.length;i++){
                  lazyloadObser.observe(imgs[i])
              } 
            }
    </script>
</body>
</html>